package com.gopay.scheduler.job;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.gopay.common.constants.mail.MailLevel;
import com.gopay.common.domain.mail.Send;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.user.UserSmsRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.job.vo.CustInfo;
import com.gopay.scheduler.mail.MailEngine;
import com.gopay.scheduler.service.cacert.CustCaCertService;
import com.gopay.sms.client.GopaySMSHttpClient;
import com.gopay.sms.common.constants.SMSAppId;
import com.gopay.sms.common.domain.RequestVO;
import com.gopay.sms.common.domain.ResponseVO;

import net.sf.json.JSONObject;

/**
 * 客户数字证书更新提醒job
 * 
 * @CustCaCertUpdateRemind.java
 * @author xuangh
 * @2016年2月15日 下午4:15:44 www.gopay.com.cn Inc.All rights reserved.
 */
public class CustCaCertNotifyRemindJob extends GopayBaseJob {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
    private @Value("#{webProperties['portal.url']}")
    String portalUrl; // 此处暂时使用portalUrl
	@Resource(name = "custCaCertServiceCron")
	private CustCaCertService certService;
	@Resource(name = "userSmsRemoteClient")
	private UserSmsRemoteService userSmsRemoteClient;
    @Resource(name = "mailEngine")
    private MailEngine mailEngine;

	@Override
	protected void doJobInternal() {
		logger.error("custCaCertNotifyRemindJob------------start---------");
		logger.error("开始处理数字证书过期提醒任务");
		/**
		 * 提前1个月通过手机或邮箱进行提醒（用户若使用手机号注册或用邮箱注册绑定过手机号的则通过短信通知， 如用邮箱注册则发送通知至用户注册邮箱）
		 */
		List<CustInfo> custList = certService.getCustList();
        if (custList != null && custList.size() > 0) {
            logger.error("查询获取到的过期数字证书的数量为： " + custList.size());
            int successCount = 0;
            for (CustInfo custInfo : custList) {
                try {
                    if ("2".equals(custInfo.getCustType())) {
                        // 企业财务员
                        if (!"999".equals(custInfo.getOperId() )) {
                            logger.error("企业财务员发送手机号: " + custInfo.getOperMobile() +",userId: "+custInfo.getUserId());
                            if (StringUtils.isNotEmpty(custInfo.getOperMobile())) {
                                sendSms(custInfo.getOperMobile(), custInfo.getValidTo());
                            }
                        } else if(StringUtils.isNotEmpty(custInfo.getCustEmail())) {
                            // 企业邮箱不为空，发送邮件提醒
                            logger.error("企业发送邮箱为: " + custInfo.getCustEmail()+",userId: "+custInfo.getUserId());
                            sendMail(custInfo.getCustEmail(), custInfo.getCustName(), custInfo.getValidTo());
                        } else{
                            logger.error("企业发送手机号为: " + custInfo.getCustPhone()+",userId: "+custInfo.getUserId());
                            sendSms(custInfo.getCustPhone(), custInfo.getValidTo());
                        }
                    } else {

                        if (StringUtils.isNotEmpty(custInfo.getCustPhone())) {

                            logger.error("个人发送手机号: " + custInfo.getCustPhone());
                            sendSms(custInfo.getCustPhone(), custInfo.getValidTo());

                        } else if (StringUtils.isNotEmpty(custInfo.getCustEmail())) {
                            logger.error("个人发送邮箱为: " + custInfo.getCustEmail());
                            sendMail(custInfo.getCustEmail(), custInfo.getCustName(), custInfo.getValidTo());
                        }
                    }
                    successCount++;
                    logger.info("第" + successCount + "条通知成功,certId: " + custInfo.getCertId());

                } catch (GopayException e) {
                    logger.error("通知用户数字证书失败,userId: "+custInfo.getUserId() +",certId: "+custInfo.getCertId());
                    logger.error(e.getMessage());
                } catch (Exception e) {
                    logger.error("通知用户数字证书失败,userId: "+custInfo.getUserId() +",certId: "+custInfo.getCertId());
                    logger.error(e.getMessage());
                }
            }
            logger.error("修改成功数： " + successCount);
            logger.error("处理用户数字证书过期提醒结束。");
        } else {
            logger.info("数字证书过期提醒任务未找到需要提醒的数据");
        }

	}

	/**
	 * 发送短信
	 * @param mobile
	 * @param limitDate
	 * @throws GopayException 
	 */
	private void sendSms(String mobile, Date limitDate) throws GopayException {
		String remidDdate = DateUtils.format(limitDate, "yyyy-MM-dd");
		
		RequestVO req = new RequestVO();
		req.setAppId(SMSAppId._90001.value);
		req.setMobile(mobile);
		req.setContent("您的数字证书将于" + remidDdate + "到期，"
						+ "为确保您的交易安全及账户出款业务可以正常使用，请在到期日前登录国付宝账户进行更新。 ");
		ResponseVO resp = GopaySMSHttpClient.getInstance()
				.createVerificationCode(req);

		if (resp != null) {
			if ("100".equals(resp.getStatusCode())) {
				logger.error("短信提醒数字证书过期，已经发送成功！");
			} else {
				logger.error("短信提醒数字证书过期，发送失败！，原因：" + resp.getMessage());
				throw new GopayException("短信提醒数字证书过期，发送失败！，原因：" + resp.getMessage());
			}
		}
	}
	private void sendMail(String Email,String custName,Date limitDate) throws GopayException{
		  String email = Email.trim().toLowerCase();
		  String remidDdate = DateUtils.format(limitDate, "yyyy-MM-dd");
          Send send = new Send();
          send.setReceivers(email);// 收件人
          send.setTemplate("custCaCertRemind");
          send.setLevel(MailLevel.MID);
          Map<String, Object> json = new HashMap<String, Object>();
          json.put("replacethistotheUSERNAME", custName);
          json.put("replacethistotheLogoAddr", portalUrl);
          json.put("replacethistotheLimitDate", remidDdate);
          send.setContent(JSONObject.fromObject(json).toString());
          certService.sendMail(send);
	}

	/**
	 * @return the portalUrl
	 */
	public String getPortalUrl() {
		return portalUrl;
	}

	/**
	 * @param portalUrl the portalUrl to set
	 */
	public void setPortalUrl(String portalUrl) {
		this.portalUrl = portalUrl;
	}
    
}

